import Util from 'util';

/**
 * 用户
 */
class User {
    constructor(appVersion) {
        this.appVersion = appVersion

        this.userInfo = wx.getStorageSync(this._getUserStorageKey()) || {} // 用户信息
        this.sessionInfo = wx.getStorageSync(this._getSessionStorageKey()) || '' // session信息
    }

    // 用户存储的key
    _getUserStorageKey() {
        return 'user_' + this.appVersion + '_info'
    }

    // 用户session的key
    _getSessionStorageKey() {
        return 'session_' + this.appVersion + '_info'
    }

    // 设置用户存储
    setUserStorage(data) {
        wx.setStorageSync(this._getUserStorageKey(), data)

        this.userInfo = wx.getStorageSync(this._getUserStorageKey()) || {}
    }

    _setSessionStorage(data) {
        wx.setStorageSync(this._getSessionStorageKey(), data)

        this.sessionInfo = wx.getStorageSync(this._getSessionStorageKey()) || ''
    }

    // 检验是否存在session
    checkSession() {
        return this.getSessionKey()
    }

    // 执行登录
    authorize() {
        return new Promise((resolve, reject) => {
            this.wxLogin().then((resolveResponse) => { // 加载首页菜单数据
                wx.clearStorageSync()
                try {
                    this.setUserStorage(resolveResponse.data.igWuser)
                    this._setSessionStorage(resolveResponse.data.sessionKey)
                } catch (e) {
                    console.log(e, resolveResponse)
                }

                return resolve({});
            }, (rejectResponse) => {
                let errorMsg = '登录失败，请稍后重试...'
                if (rejectResponse.data && rejectResponse.data.error) {
                    errorMsg = rejectResponse.data.error
                }

                wx.showModal({
                    title: '提示',
                    content: errorMsg,
                    complete: () => {
                        return reject(rejectResponse); // 将错误信息回递给外部逻辑
                    }
                })
            })
        })
    }

    /**
     * 确认登录，返回是否执行了登录
     */
    login() {
        return new Promise((resolve, reject) => {
            if (!this.checkSession()) {
                this.authorize().then(() => {
                    resolve({ dologin: true })
                }, (err) => {
                    reject(err)
                })
            } else {
                resolve({ dologin: false })
            }
        })
    }

    /**
     * 用户授权登录，获取用户信息
     */
    wxLogin() {
        return new Promise((resolve, reject) => {
            wx.login({
                success: (res) => {
                  console.log(res.code);
                    if (!res.code) {
                        return reject('获取用户登录态失败！' + res.errMsg)
                    } else {
                        // 申请用户授权
                        wx.getUserInfo({
                            success: function (userRst) {
                                // var userInfo = userRst.userInfo
                                
                                let wxReqData = {
                                    encryptedData: userRst.encryptedData,
                                    iv: userRst.iv,
                                    code: res.code
                                }
                                // 后台处理用户信息
                                getApp().RPCService.wechatSignUp(wxReqData).then((userResData) => {
                                    console.log(userResData);
                                    return resolve(userResData);

                                }, (rejectResponse) => {
                                    return reject(rejectResponse);
                                })
                            },
                            fail: (res) => {
                                // 用户拒绝授权则弹出提示
                                wx.showModal({
                                    title: 'in小程序',
                                    content: '本程序大部分功能需要授权才可以使用，请允许授权',
                                    success: (res) => {
                                        if (res.confirm) {
                                            wx.openSetting()
                                        } else {
                                            wx.redirectTo({
                                                url: '/pages/errors/autherror',
                                            })
                                        }
                                    },
                                    fail: (err) => {
                                        return reject(err)
                                    }
                                })
                            }
                        })
                    }
                },

                fail: (res) => {
                    return reject(res);
                }
            });
        })
    }

    getUserId() {
        return this.userInfo.userId || '';
    }

    getName() {
        return this.userInfo.nickname || '';
    }

    getOpid() {
        return this.userInfo.openid || '';
    }

    getUserType() {
        return this.userInfo.userType || 0;
    }

    getSavePath() {
        return this.userInfo.avatarurl || '/assets/images/user.png';
    }

    getSessionKey() {
        return this.sessionInfo || ''
    }

}

export default User;